import { create } from "zustand";
import { persist, createJSONStorage } from "zustand/middleware";
import {
  getStorageSync,
  setStorageSync,
  removeStorageSync,
} from "@tarojs/taro";

// 定义storage操作
const asyncLocalStorage = {
  getItem: getStorageSync,
  setItem: setStorageSync,
  removeItem: removeStorageSync,
};

type TGlobalVarProps = {
  windowInfo?: Record<string, any>;
  [key: string]: unknown;
};

/**
 * 全局变量存储(当前会话有效)
 */
export const useGlobalVarStore = create<{
  globalVar: TGlobalVarProps;
  setGlobalVar: (_var: Record<string, any>) => void;
}>()(
  persist(
    (set, _get) => ({
      globalVar: {},
      setGlobalVar: (_var: Record<string, any>) =>
        set((state) => ({ globalVar: { ...state.globalVar, ..._var } })),
    }),
    {
      name: "global-var-storage", // 存储key名称
      partialize: (state) => ({ globalVar: state.globalVar }),
      storage: createJSONStorage(() => asyncLocalStorage),
    }
  )
);

/**
 * 用户授权token
 */
export const useTokenStore = create<{
  token: string;
  setToken: (_t: string) => void;
}>()(
  persist(
    (set, _get) => ({
      token: "",
      setToken: (_token: string) => set(() => ({ token: _token })),
    }),
    {
      name: "token-storage", // unique name
      storage: createJSONStorage(() => asyncLocalStorage),
    }
  )
);
